package com.fengzuxiao.weatherdemo;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.fengzuxiao.weatherdemo.bean.WeatherBean;
import com.fengzuxiao.weatherdemo.db.DBManger;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class WeatherFragment extends BaseFragment implements View.OnClickListener {

    TextView tempTv, cityTv, conditionTv, windTv, tempRangeTv, dateTv, Tv1, Tv2, Tv3, Tv4, Tv5;
    ImageView dayIv;
    LinearLayout futureLayout;

    /**
     * http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=FkPhtMBK0HTIQNh7gG4cNUttSTyr0nzo
     */
    String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=";
    String url2 = "&output=json&ak=FkPhtMBK0HTIQNh7gG4cNUttSTyr0nzo";
    private List<WeatherBean.ResultsBean.IndexBean> indexList;

    String city;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_weather, container, false);
        initView(view);
        //可以通过activity传值获取到当前fragment加载的是那个地方的天气情况
        Bundle bundle = getArguments();
        city = bundle.getString("city");
        String url = url1 + city + url2;
        //调用父类获取数据的方法
        loadData(url);

        return view;
    }

    @Override
    public void onSuccess(String result) {
        //解析并展示数据
        parseShowData(result);
        //更新数据
        int i = DBManger.updateInfoCity(city, result);
        if (i <= 0) {
            //更新数据库失败，说明没有这条城市信息，增加这个城市记录
            DBManger.addCityInfo(city, result);
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        //数据库当中查找上一次信息显示在Fragment当中
        String s = DBManger.queryInfoByCity(city);
        if (!TextUtils.isEmpty(s)) {
            parseShowData(s);
        }
    }

    private void parseShowData(String result) {

        //使用gson解析数据
        WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
        WeatherBean.ResultsBean resultsBean = weatherBean.getResults().get(0);
        //获取指数信息集合列表
        indexList = resultsBean.getIndex();
        //设置TextView
        dateTv.setText(weatherBean.getDate());
        cityTv.setText(resultsBean.getCurrentCity());
        //获取今日天气
        WeatherBean.ResultsBean.WeatherDataBean todayDataBean = resultsBean.getWeather_data().get(0);
        windTv.setText(todayDataBean.getWind());
        tempRangeTv.setText(todayDataBean.getTemperature());
        conditionTv.setText(todayDataBean.getWeather());
        //获取实时天气温度，需处理字符串
        String[] split = todayDataBean.getDate().split("：");
        String todayTemp = split[1].replace(")", "");
        tempTv.setText(todayTemp);
        //设置显示的天气情况图片
        Picasso.with(getActivity()).load(todayDataBean.getDayPictureUrl()).into(dayIv);

        //获取未来三天的天气情况，加载到layout中
        List<WeatherBean.ResultsBean.WeatherDataBean> futureList = resultsBean.getWeather_data();
        futureList.remove(0);
        for (int i = 0; i < futureList.size(); i++) {
            View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_center, null);
            itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            futureLayout.addView(itemView);
            TextView iTv1 = itemView.findViewById(R.id.tv_t1);
            TextView iTv2 = itemView.findViewById(R.id.tv_t2);
            TextView iTempTv = itemView.findViewById(R.id.tv_temp);
            ImageView iconIv = itemView.findViewById(R.id.iv_icon);

            //获取对应的位置天气情况
            WeatherBean.ResultsBean.WeatherDataBean dataBean = futureList.get(i);
            iTv1.setText(dataBean.getDate());
            iTv2.setText(dataBean.getWeather());
            iTempTv.setText(dataBean.getTemperature());
            Picasso.with(getActivity()).load(dataBean.getDayPictureUrl()).into(iconIv);
        }


    }

    private void initView(View view) {
        tempTv = view.findViewById(R.id.frag_tv_temp);
        cityTv = view.findViewById(R.id.frag_tv_city);
        conditionTv = view.findViewById(R.id.frag_tv_condition);
        windTv = view.findViewById(R.id.frag_tv_wind);
        tempRangeTv = view.findViewById(R.id.frag_tv_temprange);
        dateTv = view.findViewById(R.id.frag_tv_date);
        Tv1 = view.findViewById(R.id.frag_tv1);
        Tv2 = view.findViewById(R.id.frag_tv2);
        Tv3 = view.findViewById(R.id.frag_tv3);
        Tv4 = view.findViewById(R.id.frag_tv4);
        Tv5 = view.findViewById(R.id.frag_tv5);
        dayIv = view.findViewById(R.id.frag_iv_today);
        futureLayout = view.findViewById(R.id.frag_center_layout);

        Tv1.setOnClickListener(this);
        Tv2.setOnClickListener(this);
        Tv3.setOnClickListener(this);
        Tv4.setOnClickListener(this);
        Tv5.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        switch (v.getId()) {
            case R.id.frag_tv1:
                builder.setTitle("穿衣指数");
                WeatherBean.ResultsBean.IndexBean indexBean = indexList.get(0);
                String msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_tv2:
                builder.setTitle("洗车指数");
                indexBean = indexList.get(1);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_tv3:
                builder.setTitle("感冒指数");
                indexBean = indexList.get(2);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_tv4:
                builder.setTitle("运动指数");
                indexBean = indexList.get(3);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
            case R.id.frag_tv5:
                builder.setTitle("紫外线指数");
                indexBean = indexList.get(4);
                msg = indexBean.getZs() + "\n" + indexBean.getDes();
                builder.setMessage(msg);
                builder.setPositiveButton("确定", null);
                break;
        }
        builder.create().show();
    }
}
